<template>
  <div class="new-navbar-wrapper" style="background-color: #01182d">
    <img :src="$store.state.settings.settings.systemIcon" alt="log" class="left-logo" />
    <div class="content-div">
      <div></div>
      <div style="flex: 1"></div>
      <div
        v-if="permissionsMenuList && permissionsMenuList.length > 0"
        class="content-to-index"
        style="margin-right: 24px; height: 35px; padding-left: 15px; padding-right: 15px"
        @click="toDashboard"
      >
        <img src="@/assets/icons/hr_fff_houtai.png" alt style="width: 12px; height: 12px; margin-right: 4px" />
        <span class="content-to-index-font">返回操作后台</span>
      </div>
    </div>
    <div class="navbar-wrapper-right">
      <div class="nav-right-wrapper border-no-left">
        <a-popover placement="bottomRight">
          <template slot="content">
            <!-- 消息切换 -->
            <div slot="overlay" ref="noticeDropdown" class="overlay-wrapper">
              <a-tabs default-active-key="1" class="overlay-tab-wrapper" @change="changeTab">
                <a-tab-pane key="1">
                  <span slot="tab">
                    消息通知
                    <span
                      v-if="noNotice"
                      class="ant-badge ant-badge-status ant-badge-not-a-wrapper"
                      style="position: absolute; top: 10px; right: 0px"
                    >
                      <span class="ant-badge-status-dot ant-badge-status-red" />
                      <span class="ant-badge-status-text" />
                    </span>
                  </span>
                  <div class="notice-wrapper">
                    <div class="Top_classify_warp">
                      <div class="Top_classify" :class="classify === 10086 ? 'active' : ''" @click="onClassify(10086, '')">全部</div>
                      <div
                        :class="classify === index ? 'active' : ''"
                        v-for="(item, index) in TopData"
                        :key="index"
                        @click="onClassify(index, item.id)"
                        class="Top_classify"
                      >
                        {{ item.name }}
                      </div>
                    </div>
                    <!-- 消息列表 -->
                    <div class="mamessageList">
                      <div
                        v-if="noticeList.length === 0"
                        style="width: 100%; height: 100%; display: flex; justify-content: center; align-items: center"
                      >
                        <a-empty />
                      </div>

                      <a-list v-else item-layout="horizontal" :data-source="noticeList">
                        <a-list-item slot="renderItem" slot-scope="item" @click="read(item)" style="cursor: pointer">
                          <div class="notice_wrapper">
                            <div class="item-left">
                              <div
                                :class="
                                  item.readStatus
                                    ? 'bac-6D69F71A-radius-2px-gray font-6A66F6-10px-gray'
                                    : 'bac-6D69F71A-radius-2px font-6A66F6-10px'
                                "
                                style="
                                  min-width: 40px;
                                  margin-right: 10px;
                                  padding-left: 5px;
                                  padding-right: 8px;
                                  padding-top: 5px;
                                  padding-bottom: 5px;
                                "
                              >
                                {{ item.title }}
                              </div>
                              <div :class="item.readStatus ? 'yidu' : 'weidu'">{{ item.title }}</div>
                            </div>
                            <div class="weidu">{{ item.gmtCreate ? formatDateAll(item.gmtCreate, "d") : "--" }}</div>
                          </div>
                        </a-list-item>
                      </a-list>
                    </div>
                  </div>
                </a-tab-pane>
              </a-tabs>

              <div class="footer-overlay footer-overlays">
                <a-button type="link" @click="readAllClick">
                  全部已读
                  <a-icon type="check-circle" />
                </a-button>
                <div style="height: 50px; border-right: 1px solid #d4d2d2"></div>
                <a-button type="link" @click="getMore">
                  查看更多
                  <a-icon type="right" />
                </a-button>
              </div>
            </div>
          </template>

          <span class="notice-bell">
            <img v-if="!noNotice" src="@/assets/icons/notice.png" alt />
            <img v-else src="@/assets/icons/notice2.png" alt />
          </span>
        </a-popover>

        <a-dropdown :trigger="['hover']" placement="bottomRight" class="avatar-dropdown">
          <div class="avatar-wrapper">
            <img :src="avatar" class="avatar-img" />
          </div>
          <!-- 新版头像 -->
          <a-menu slot="overlay" :default-selected-keys="defaultSelectedKeys">
            <a-menu-item key="0" @click="goPerson">
              <div class="item-div">
                <img :src="avatar" class="avatar-img-com" />
                <span class="item-span title-name ove">{{ name }}</span>
                <a-icon class="avatar-mid-right jt" type="right" />
              </div>
            </a-menu-item>
            <a-menu-divider style="background: #f2f2f2" />
            <a-menu-item key="1" @click="logout">
              <a-icon type="poweroff" />
              <span class="pd_l4">退出登录</span>
            </a-menu-item>
            <a-menu-item v-if="showShangbao" key="shangbao" @click="goShangbao">
              <span>保险公司端-商保</span>
            </a-menu-item>
            <a-menu-item v-if="showConsole" key="console">
              <a href="#/console">打开控制台</a>
            </a-menu-item>
            <template v-if="permissions_site.length > 0">
              <a-menu-divider style="background: #f2f2f2" />
              <a-menu-item v-for="(site, index) in permissions_site" :key="(index + 2).toString()">
                <div class="item-div" @click="switchSite(site)">
                  <a-icon type="shop" />
                  <span class="item-span ove">{{ site.name }}</span>
                </div>
              </a-menu-item>
            </template>
          </a-menu>
        </a-dropdown>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters, mapState } from "vuex";
import { listAllNotices, readAllSysNotice, readAllNotice, listAllGroup, readItem } from "@/api/company/index";
import adminMenuMap from "@/router/adminMenuMap";
export default {
  name: "Navbar",
  props: {
    aMenu: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      groupid: "",
      classify: 10086,
      TopData: [],
      noticeList: [],
      companyId: this.$store.state.hr.companyId,
      noNotice: true,
      showOverLay: false,
      currentKey: 1,
      pMenu: []
    };
  },
  computed: {
    ...mapGetters(["sidebar", "avatar", "name", "permissions_site", "permissions_menu"]),
    ...mapGetters({ ACTIVECOMPANYNAME: "admin/ACTIVECOMPANYNAME" }),
    ...mapState(["settings", "consolePermission", "auth", "hr"]),
    showShangbao() {
      if (this.auth && this.auth.permissions && this.auth.permissions.moduleList && this.auth.permissions.moduleList.length > 0) {
        if (this.auth.permissions.moduleList.filter((item) => item.moduleType === "insurance").length > 0) {
          return true;
        }
      }
      return false;
    },
    showConsole() {
      if (this.auth && this.auth.permissions && this.auth.permissions.moduleList && this.auth.permissions.moduleList.length > 0) {
        if (this.auth.permissions.moduleList.filter((item) => item.moduleType === "supper").length > 0) {
          if (this.consolePermission && this.consolePermission.menuList && this.consolePermission.menuList.length > 0) {
            return true;
          }
        }
      }
      return false;
    },
    defaultSelectedKeys() {
      return this.permissions_site
        .map((item, index) => {
          item["index"] = index + 2;
          return item;
        })
        .filter((item, index) => {
          return item.currSite === true;
        })
        .map((item) => item.index.toString());
    },
    adminNavState() {
      return this.hr.adminNavState;
    },
    permissionStringList() {
      return this.auth.permissions.permissionStringList;
    },
    permissionsMenuList() {
      return this.auth.permissions.menuList;
    },
    authLoaded() {
      return this.auth.loaded;
    }
  },
  watch: {
    aMenu: {
      handler(newName) {
        this.pMenu = newName;
      },
      immediate: true
    }
  },
  created() {
    this.getListAllGroup();
    this.initNotices();
    this.initAdminNavState();
  },
  comments() {},
  methods: {
    goShangbao() {
      sessionStorage.setItem("shangbaoPageState", "company");
      const { href } = this.$router.resolve({
        path: "/shangyebaoxian"
      });
      window.open(href, "_blank");
    },
    initAdminNavState() {
      const idx = Object.values(adminMenuMap).findIndex((item) => item.router === this.$route.path);
      if (idx > -1) {
        const item = Object.values(adminMenuMap)[idx];
        this.$store.commit("hr/setAdminNavState", item.belong);
      }
    },
    gotoUrlPath(url) {
      this.$router.push(url);
    },
    async read(item) {
      const company = await this.$store.dispatch("hr/findCompanyItem", item.subjectId);
      const comyName = company ? company.name : null;
      // 保存用工单位信息
      this.$store.dispatch("onCompanyClick", {
        id: item.subjectId,
        name: comyName
      });
      // sessionStorage.setItem("selectTreeId", item.subjectId);
      // sessionStorage.setItem("siteName", comyName);
      // sessionStorage.setItem("siteId", item.subjectId);

      if (!item.readStatus) {
        const h = [];
        h.push(item.id);
        readItem(h)
          .then((res) => {
            item.readStatus = true;
            if (item.toUrl) {
              this.gotoUrlPath(item.toUrl);
            } else {
              if (item.subjectId === "defaultTransferAccounts") {
                this.gotoPath(item.subjectId, item.title);
              } else {
                this.gotoPath(item.noticeTypeCode);
              }
            }
          })
          .catch((err) => {
            console.log("ERROR", err);
          });
      } else {
        if (item.toUrl) {
          this.gotoUrlPath(item.toUrl);
        } else {
          if (item.subjectId === "defaultTransferAccounts") {
            this.gotoPath(item.subjectId, item.title);
          } else {
            this.gotoPath(item.noticeTypeCode);
          }
        }
      }
    },
    gotoPath(type, title) {
      switch (type) {
        case "turnOfficial":
          // return "人员转正";
          this.$router.push({
            path: "/staff/manger", // 员工异动
            query: { selectId: "2" }
          });
          break;
        case "transfer":
          // return "人员调岗";
          this.$router.push({
            path: "/staff/manger", // 员工异动
            query: { selectId: "5" }
          });
          break;
        case "resign":
          // return "人员离职";
          this.$router.push({
            path: "/staff/manger", // 员工异动
            query: { selectId: "4" }
          });
          break;
        case "salaryCardChange":
          // return "工资卡信息变更";
          this.$router.push({
            path: "/staff/employee"
          });
          break;
        case "induction":
          // return "人员入职";
          this.$router.push({
            path: "/staff/manger", // 员工异动
            query: { selectId: "1" }
          });
          break;
        case "increment":
          // return "增减员确认";
          this.$router.push({
            path: "/shebao/shebaoManage" // 员工异动
          });
          var that = this;
          setTimeout(function () {
            that.$router.push({
              path: "/shebao/shebaoManage/shebaoZengJianY"
            });
          }, 700);
          break;
        case "approval":
          // return "审批通知";

          this.$router.push({
            path: "/approval/list"
          });
          break;
        case "contractExpires":
          // return "合同到期";
          this.$router.push({
            path: "/contract/elecontract"
          });
          break;
        case "defaultTransferAccounts":
          // return "一键发薪审核";
          if (title === "审批抄送通知") {
            this.$router.push({
              path: "/paySalary/examine?changeKey=4"
            });
          } else {
            this.$router.push({
              path: "/paySalary/examine?changeKey=1"
            });
          }
          break;
        // case "memoRemind":
        //   return "备忘提醒";
      }
    },
    getListAllGroup() {
      listAllGroup({ companyId: this.$store.state.hr.companyId })
        .then((res) => {
          this.TopData = res.data.filter((item) => item.noticeTypeList);
        })
        .catch((err) => {
          console.log("ERROR", err);
        });
    },
    onClassify(index, id) {
      this.classify = index;
      this.groupid = id;
      this.initNotices();
    },
    goPerson() {
      this.$router.push("/auth/config");
    },
    async logout() {
      this.$store.commit("hr/setAdminNavState", "workbench");

      localStorage.clear();
      sessionStorage.clear();

      await this.$store.dispatch("auth/logout");
      this.$router.push(`/auth/login`);
    },
    async switchSite(site) {
      if (!site.currSite) {
        if (this.$route.path !== "/dashboard") {
          await this.$router.push("/");
        }
        this.$store
          .dispatch("auth/switchSite", site.id, site.name)
          .then(() => {
            localStorage.setItem("switchSite", "true");
            location.reload();
          })
          .catch((err) => {
            console.log("ERROR", err);
          });
      }
    },
    changeTab(key) {
      this.currentKey = key;
      this.showOverLay = true;
      this.initNotices();
    },
    getMore() {
      this.showOverLay = false;
      this.$router.push({
        path: "/notice"
      });
    },
    initNotices() {
      listAllNotices({
        moduleType: "hr",
        groupId: this.groupid
      }).then((res) => {
        this.noticeList = res.data.entities || [];
        const unReadList = this.noticeList.filter((item) => item.readStatus === false);
        if (unReadList.length > 0) {
          this.noNotice = true;
        } else {
          this.noNotice = false;
        }
      });
    },
    readAllClick() {
      this.$confirm({
        title: "确定全部设置为已读吗?",
        okType: "warning",
        onOk: () => {
          this.showOverLay = false;
          if (this.currentKey === 1) {
            readAllNotice({ moduleType: "hr", companyId: this.companyId })
              .then((res) => {
                this.$message.success("操作成功");
                this.initNotices();
              })
              .catch((err) => {
                console.log("ERROR", err);
              });
          } else {
            readAllSysNotice({ moduleType: "hr", companyId: this.companyId })
              .then((res) => {
                this.$message.success("操作成功");
                this.initNotices();
              })
              .catch((err) => {
                console.log("ERROR", err);
              });
          }
        }
      });
    },
    toDashboard() {
      this.$store.commit("hr/setAdminNavState", "workbench");
      const menus = this.permissions_menu.map((item) => item.url);
      if (menus.includes("/dashboard")) {
        this.$router.push("/dashboard");
      } else {
        const operationMenus = this.permissions_menu.filter((item) => item.url !== "/dashboard" && item.level > 1);
        const operationMenusUrls = operationMenus.map((item) => item.url);
        this.$router.push(operationMenusUrls[0]);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.bottom-indicator {
  width: 24px;
  height: 3px;
  background: #ffffff;
  margin: 0 auto;
  margin-top: -10px;
}
.bac-6D69F71A-radius-2px {
  background: var(--primary10);
  border-radius: 3px;
}
.bac-6D69F71A-radius-2px-gray {
  background: #9f9fa21e;
  border-radius: 3px;
}
.font-6A66F6-10px {
  font-size: 8px;
  font-weight: 500;
  color: var(--primary);
  line-height: 15px;
}
.font-6A66F6-10px-gray {
  font-size: 8px;
  font-weight: 500;
  color: #9fa2a8;
  line-height: 15px;
}
.iconfont {
  color: var(--primary);
}
.colors {
  display: flex;
  flex-direction: column;
}
.avatar-img-com {
  width: 44px;
  height: 44px;
  border-radius: 50%;
}
.title-name {
  font-weight: 600;
  font-size: 20px;
}

.ant-dropdown .ant-dropdown-menu-item,
.ant-dropdown .ant-dropdown-menu-submenu-title {
  padding: 10px 16px 10px 24px;
}
.ant-dropdown-menu-item:hover,
.ant-dropdown-menu-submenu-title:hover {
  color: var(--primary);
}
.item-span {
  display: inline-block;
  width: 100%;
  padding-left: 12px;
}
.jt {
  color: #c1c1c1;
}
.item-div {
  align-items: center;
  display: flex;
}
.active {
  background: var(--primary) !important;
  color: #ffffff;
}
.Top_classify_warp {
  width: 550px;
  display: flex;
  flex-wrap: wrap;
  .Top_classify {
    margin-right: 5px;
    margin-left: 5px;
    margin-top: 10px;
    padding: 5px 15px;
    border-radius: 16px;
    background: #f0f0f0;
    cursor: pointer;
    user-select: none;
  }
}
.footer-overlays {
  border-top: 1px solid #d4d2d2;
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.mamessageList {
  height: 300px;
  margin: 15px 0;
  overflow-y: auto;
}
.notice_wrapper {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.item-left {
  display: flex;
  align-items: center;
}
</style>
